package com.gr.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gr.entity.Category;
import com.gr.entity.ResultEntity;
import com.gr.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品三级分类 前端控制器
 * </p>
 *
 * @author guoran
 * @since 2022-05-11
 */
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    ICategoryService categoryService;
    @GetMapping("/selectChildrenCategory/{categoryId}")
    public ResultEntity<List<Category>> selectChildrenCategory(@PathVariable("categoryId")Long categoryId){
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("parent_id",categoryId);
        List<Category> childList = categoryService.list(wrapper);
        return ResultEntity.ok(childList);
    }

    @PostMapping("/add")
    public ResultEntity add(@RequestBody Category category){
        categoryService.save(category);
        return ResultEntity.ok();
    }

    @DeleteMapping("/delete/{categoryId}")
    public ResultEntity delete(@PathVariable("categoryId")Long categoryId){
        categoryService.removeById(categoryId);
        return ResultEntity.ok();
    }

    @GetMapping("/selectOne/{categoryId}")
    public ResultEntity<Category> selectOne(@PathVariable("categoryId")Long categoryId){
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("category_id",categoryId);
        Category one = categoryService.getOne(wrapper);
        return ResultEntity.ok(one);
    }

    @PutMapping("/update")
    public ResultEntity update(@RequestBody Category category){
        categoryService.updateById(category);
        return ResultEntity.ok();
    }

    @GetMapping("/selectTree")
    public ResultEntity<List<Category>> selectTree(){
        List<Category> categories = categoryService.list();
        List<Category> firstLevelList = categories.stream().filter((category) -> {
            return category.getParentId().equals(0l);//Long类型0也要加l
        }).peek((category)->{//根据父类别的id，找到该父类别对应的子类别，单独定义出来一个方法
            List<Category> children = getChildrenByPid(category.getCategoryId(), categories);
            category.setCategoryList(children);
        }).collect(Collectors.toList());
        return ResultEntity.ok(firstLevelList);
    }

    private List<Category> getChildrenByPid(Long pid,List<Category> categories){
        return categories.stream().filter((resource) -> {
            return resource.getParentId().equals(pid);//小坑
        }).peek((category)->{//给属性赋值
            //想办法找到category对象的孩子就好了,list集合放入参数
            List<Category> list = getChildrenByPid(category.getCategoryId(), categories);//递归，会依次找孩子，循环到没有孩子
            category.setCategoryList(list);//给二级菜单对应的三级菜单赋值
        }).collect(Collectors.toList());
    }
}

